package com.hfy.music.service.impl;

import cn.hutool.core.bean.BeanUtil;
import com.hfy.model.dto.RecentDto;
import com.hfy.model.vo.MusicVo;
import com.hfy.music.mapper.RecentMusicMapper;
import com.hfy.music.service.RecentMusicService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;
import result.Result;

import java.util.List;

import static constants.OtherConstants.RECENT_MUSIC_MAX_NUM;
import static utils.MusicConverter.getMusicResult;

/**
 * @ author 韩
 * time: 2024/5/30 19:39
 */
@Service
public class RecentMusicServiceImpl implements RecentMusicService {

    @Autowired
    private RecentMusicMapper recentMusicMapper;

    @Override
    public Result addRecent(RecentDto dto) {
        // 逻辑放在了存储过程中
//        recentMusicMapper.addRecent(dto.getAccount(),dto.getMusicId());
        if (BeanUtil.isEmpty(dto)) {
            return Result.error("参数不许为空");
        }
        Long account = dto.getAccount();
        Integer musicId = dto.getMusicId();
        // 先删除相同数据
        recentMusicMapper.deleteSame(account, musicId);
        // 检查用户播放记录的数量
        Integer count = recentMusicMapper.queryRecentNum(account);
        // 删除最旧的记录（时间戳最早的）
        if (count >= RECENT_MUSIC_MAX_NUM) {
            recentMusicMapper.deleteOldest(account);
        }
        // 插入新记录，timestamp 字段会自动设置为当前时间
        recentMusicMapper.insertNewRecord(account,musicId);
        return Result.ok("已成功添加到最近播放中");
    }

    @Override
     public Result queryRecent(Long account) {
        List<MusicVo> musicList = recentMusicMapper.queryRecent(account);

        return getMusicResult(musicList);
    }



    @Override
    public Result queryRecentNum(Long account) {
        Integer num = recentMusicMapper.queryRecentNum(account);
        return Result.ok(num);
    }

}
